package top.easyblog.core.config;

import org.redisson.Redisson;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author: frank.huang
 * @date: 2023-12-24 19:05
 */
@Configuration
public class RedissonBloomFilterConfiguration {


    private static final int DEFAULT_REDIS_DB = 0;

    @Autowired
    private CustomConfiguration configuration;

    @Bean
    @ConditionalOnMissingBean
    public RBloomFilter<String> rBloomFilter(RedisProperties redisProperties) {
        Config config = new Config();
        config.useSingleServer().setAddress(String.format("redis://%s:%s", redisProperties.getHost(), redisProperties.getPort()))
                .setPassword(redisProperties.getPassword()).setDatabase(DEFAULT_REDIS_DB);
        RedissonClient redissonClient = Redisson.create(config);
        RBloomFilter<String> bloomFilter = redissonClient.getBloomFilter(configuration.getDefaultBFKey());
        bloomFilter.tryInit(configuration.getDefaultBFCapacity(), configuration.getDefaultBFErrorRate());
        return bloomFilter;
    }

}
